package com.atguigu.gulimall.ware.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.exception.NoStockException;
import com.atguigu.common.to.mq.OrderTo;
import com.atguigu.common.to.mq.StockDetailTo;
import com.atguigu.common.to.mq.StockLockedTo;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.ware.entity.WareOrderTaskDetailEntity;
import com.atguigu.gulimall.ware.entity.WareOrderTaskEntity;
import com.atguigu.gulimall.ware.fengin.OrderFeignService;
import com.atguigu.gulimall.ware.fengin.ProductFeignService;
import com.atguigu.gulimall.ware.service.WareOrderTaskDetailService;
import com.atguigu.gulimall.ware.service.WareOrderTaskService;
import com.atguigu.gulimall.ware.vo.OrderItemVo;
import com.atguigu.gulimall.ware.vo.OrderVo;
import com.atguigu.gulimall.ware.vo.SkuHasStockVo;
import com.atguigu.gulimall.ware.vo.WareSkuLockVo;
import lombok.Data;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.ware.dao.WareSkuDao;
import com.atguigu.gulimall.ware.entity.WareSkuEntity;
import com.atguigu.gulimall.ware.service.WareSkuService;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

import static com.atguigu.gulimall.ware.config.RabbitMqConfig.STOCK_EVENT_EXCHANGE;


@Service("wareSkuService")
public class WareSkuServiceImpl extends ServiceImpl<WareSkuDao, WareSkuEntity> implements WareSkuService {

    @Resource
    private WareSkuDao wareSkuDao;
    @Resource
    private ProductFeignService productFeignService;
    @Autowired
    private WareOrderTaskService wareOrderTaskService;
    @Autowired
    private WareOrderTaskDetailService wareOrderTaskDetailService;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private OrderFeignService orderFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<WareSkuEntity> page = this.page(
                new Query<WareSkuEntity>().getPage(params),
                new QueryWrapper<WareSkuEntity>()
        );
        return new PageUtils(page);
    }

    @Override
    public void addStock(Long skuId, Long wareId, Integer skuNum) {
        //1、判断如果还没有这个库存记录新增
        List<WareSkuEntity> entities = wareSkuDao.selectList(new QueryWrapper<WareSkuEntity>().eq("sku_id", skuId).eq("ware_id", wareId));
        if (entities == null || entities.size() == 0) {
            WareSkuEntity skuEntity = new WareSkuEntity();
            skuEntity.setSkuId(skuId);
            skuEntity.setStock(skuNum);
            skuEntity.setWareId(wareId);
            skuEntity.setStockLocked(0);
            //TODO 远程查询sku的名字，如果失败，整个事务无需回滚
            //1、自己catch异常
            //TODO 还可以用什么办法让异常出现以后不回滚？高级
            try {
                R info = productFeignService.info(skuId);
                Map<String, Object> data = (Map<String, Object>) info.get("skuInfo");
                if (info.getCode() == 0) {
                    skuEntity.setSkuName((String) data.get("skuName"));
                }
            } catch (Exception e) {
            }
            wareSkuDao.insert(skuEntity);
        } else {
            wareSkuDao.addStock(skuId, wareId, skuNum);
        }
    }

    @Override
    public List<SkuHasStockVo> getSkuHasStock(List<Long> skuIds) {

        // SELECT COUNT(stock - stock_locked) FROM `wms_ware_sku` WHERE sku_id = ?

        List<SkuHasStockVo> skuHasStockVos = skuIds.stream().map(skuId -> {

            Long count = baseMapper.getSkuHasStock(skuId);

            SkuHasStockVo skuHasStockVo = new SkuHasStockVo();
            skuHasStockVo.setSkuId(skuId);
            skuHasStockVo.setHasStock(count == null ? false : count > 0);

            return skuHasStockVo;
        }).collect(Collectors.toList());

        return skuHasStockVos;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean orderLockStock(WareSkuLockVo vo) {

        // 1.保存库存工作单详情信息,以便后续进行追溯
        WareOrderTaskEntity wareOrderTaskEntity = new WareOrderTaskEntity();
        wareOrderTaskEntity.setOrderSn(vo.getOrderSn());
        wareOrderTaskEntity.setCreateTime(new Date());
        wareOrderTaskService.save(wareOrderTaskEntity);

        // 2.获得商品的详细信息
        List<OrderItemVo> orderItemVos = vo.getLocks();
        // 3.获取商品的库存信息及地址
        List<SkuWareHasStock> wareHasStockList = orderItemVos.stream().map((orderItemVo) -> {
            // 内部类 封装商品的属性以及SkuID
            SkuWareHasStock skuWareHasStock = new SkuWareHasStock();
            Long skuId = orderItemVo.getSkuId();
            skuWareHasStock.setSkuId(skuId);
            skuWareHasStock.setNum(orderItemVo.getCount());
            // 查询该商品仓库中是否有货 库存需要大于等于 用户购买的数量
            List<Long> wareIds = baseMapper.listWareIdHasSkuStock(skuId);
            skuWareHasStock.setWareIds(wareIds);
            return skuWareHasStock;
        }).collect(Collectors.toList());

        // 3.进行库存锁定，有一个失败就都失败
        for (SkuWareHasStock wareHasStock : wareHasStockList) {
            // 3.1锁定是否成功标识位
            boolean skuStocked = false;
            // 3.2获取skuId和商品对应的仓库
            Long skuId = wareHasStock.getSkuId();
            // 获取有货的仓库ID
            List<Long> wareIds = wareHasStock.getWareIds();
            // 3.3没有仓库地址，代表没有货
            if (null == wareIds && wareIds.size() == 0) {
                throw new NoStockException(skuId);
            }
            // 3.4进行锁定商品
            for (Long wareId : wareIds) {
                // 锁定成功就返回1，失败就返回0
                Long count = wareSkuDao.lockSkuStock(skuId, wareId, wareHasStock.getNum());
                // 如果锁定成功
                if (count == 1L) {
                    skuStocked = true;
                    // 将锁定库存的详细信息记录下来
                    WareOrderTaskDetailEntity wareOrderTaskDetailEntity = new WareOrderTaskDetailEntity();
                    wareOrderTaskDetailEntity.setSkuId(skuId);
                    wareOrderTaskDetailEntity.setTaskId(wareOrderTaskEntity.getId());
                    wareOrderTaskDetailEntity.setWareId(wareId);
                    wareOrderTaskDetailEntity.setSkuName("");
                    wareOrderTaskDetailEntity.setSkuNum(wareHasStock.getNum());
                    wareOrderTaskDetailEntity.setLockStatus(1);
                    wareOrderTaskDetailService.save(wareOrderTaskDetailEntity);

                    // 将锁定成功的情况，发送MQ
                    StockLockedTo lockedTo = new StockLockedTo();
                    StockDetailTo detailTo = new StockDetailTo();
                    BeanUtils.copyProperties(wareOrderTaskDetailEntity, detailTo);
                    lockedTo.setId(wareOrderTaskDetailEntity.getId());
                    lockedTo.setDetailTo(detailTo);
                    // 将锁定库存的详细信息发送
                    rabbitTemplate.convertAndSend(STOCK_EVENT_EXCHANGE, "stock.locked", lockedTo);
                    break;
                } else if (count == 0L) {
                    // 锁定失败，重试下一个仓库
                    continue;
                }
            }
            if (skuStocked == false) {
                throw new NoStockException(skuId);
            }
        }
        return true;
    }

    @Override
    public void unlockStock(StockLockedTo to) {
        // 1.获得当时锁库存表保存的的信息
        StockDetailTo detailTo = to.getDetailTo();
        Long detailToId = detailTo.getId();
        /**
         * 解锁
         * 1、查询数据库关于这个订单锁定库存信息
         *   有：证明库存锁定成功了
         *      解锁：订单状况
         *          1、没有这个订单，必须解锁库存
         *          2、有这个订单，不一定解锁库存
         *              订单状态：已取消：解锁库存
         *                      已支付：不能解锁库存
         */
        // 2.获取到当时锁表的信息
        WareOrderTaskDetailEntity detailEntity = wareOrderTaskDetailService.getById(detailToId);
        if (null != detailEntity) {
            // 3.获取到当时的订单信息
            Long taskId = detailEntity.getTaskId();
            WareOrderTaskEntity taskEntity = wareOrderTaskService.getById(taskId);

            // 4.查看订单状态
            String orderSn = taskEntity.getOrderSn();
            // 调用订单远程服务，查看订单状态
            R status = orderFeignService.getOrderStatus(orderSn);
            if (status.getCode() == 0) {
                // 订单数据返回成功
                OrderVo orderInfo = status.getData(new TypeReference<OrderVo>() {
                });
                // 判断订单状态是否已取消或者支付或者订单不存在
                if (orderInfo == null || orderInfo.getStatus() == 4) {
                    // 订单已被取消，才能解锁库存
                    if (detailEntity.getLockStatus() == 1) {
                        //当前库存工作单详情状态1，已锁定，但是未解锁才可以解锁
                        unLockStock(detailTo.getSkuId(), detailTo.getWareId(), detailTo.getSkuNum(), taskId);
                    }
                }else {
                    //消息拒绝以后重新放在队列里面，让别人继续消费解锁
                    //远程调用服务失败
                    throw new RuntimeException("远程调用服务失败");
                }
            }
        }
    }

    @Override
    public void unlockStock(OrderTo orderTo) {
        // 1.获取订单号，查询工作单
        String orderSn = orderTo.getOrderSn();
        WareOrderTaskEntity taskEntity = wareOrderTaskService.queryTaskByOrderSn(orderSn);
        // 2.根据工作单，查询工作单任务详细情况, 查询到是到现在还未解锁的
        List<WareOrderTaskDetailEntity> taskDetailEntities = wareOrderTaskDetailService.queryTaskDetailByTaskId(taskEntity.getId());
        // 2.进行解锁
        taskDetailEntities.forEach((item) -> {
            unLockStock(item.getSkuId(), item.getWareId(), item.getSkuNum(), item.getTaskId());
        });
    }

    /**
     * 解锁库存
     *
     * @param skuId      商品的SKUID
     * @param wareId     仓库ID
     * @param skuNum     用户购买的数量，也就是之前锁定成功的数量
     * @param taskDetailId 锁定订单详细的ID
     */
    private void unLockStock(Long skuId, Long wareId, Integer skuNum, Long taskDetailId) {
        // 库存解锁
        baseMapper.unLockStockByData(skuId, wareId, skuNum);
        // 更新工作单的状态
        WareOrderTaskDetailEntity taskDetailEntity = new WareOrderTaskDetailEntity();
        taskDetailEntity.setId(taskDetailId);
        //变为已解锁
        taskDetailEntity.setLockStatus(2);
        wareOrderTaskDetailService.updateById(taskDetailEntity);
    }

    @Data
    class SkuWareHasStock {

        private Long skuId;
        // 用户要想购买的商品数量
        private Integer num;
        // 仓库地址ID
        private List<Long> wareIds;
    }
}